<template>
  <div class="s-cropper-container">
    <div class="s-cropper-header">
      <div class="close-btn" @click="close">
        <svg
          t="1722560409746"
          class="icon"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          p-id="6750"
          width="24"
          height="24"
        >
          <path
            d="M230.8608 544l198.8096 198.8096a32 32 0 0 1-45.2608 45.2608l-249.856-249.856a37.12 37.12 0 0 1 0-52.48l249.856-249.8048a32 32 0 0 1 45.2608 45.2608L230.8608 480H870.4a32 32 0 1 1 0 64H230.8608z"
            fill="#ffffff"
            p-id="6751"
          ></path>
        </svg>
        <div>图片裁剪</div>
      </div>
      <div @click="change">{{ loading ? "裁剪中..." : "确认" }}</div>
    </div>
    <div class="s-cropper-co" v-show="false"></div>
    <img :src="src" alt="Picture" ref="image" v-show="false" />
  </div>
</template>
<script>
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs";

export default {
  name: "CropperExample",
  props: {
    src: {
      type: String,
      default: "",
    },
  },
  emits: ["close", "change"],
  data() {
    return {
      // eslint-disable-next-line no-console
      cropper: null,
      loading: false,
    };
  },
  mounted() {
    const image = this.$refs.image;
    image.src = this.src;
    image.alt = "Picture";
    this.cropper = new Cropper(image, {
      container: ".cropper-container",
      aspectRatio: 1,
      viewMode: 1,
      autoCropArea: 1,
      dragMode: "move",
    });
    // eslint-disable-next-line no-console
    console.log(this.cropper);
    // eslint-disable-next-line
    // new VConsole();
  },
  unmounted() {
    this.cropper.destroy();
  },
  methods: {
    close() {
      this.$emit("close");
    },
    getUrl() {
      // eslint-disable-next-line
      return new Promise((resolve, _) => {
        const cropCanvasData = this.cropper.getCroppedCanvas();
        cropCanvasData.toBlob((blob) => {
          const url = URL.createObjectURL(blob);
          resolve(url);
        });
      });
    },
    async change() {
      try {
        this.loading = true;
        const url = await this.getUrl();
        this.$emit("change", url);
      } catch (error) {
        // eslint-disable-next-line
        console.log(error);
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

<style scoped>
.s-cropper-container {
  width: 100%;
  height: 100vh;
}

.s-cropper-container .s-cropper-header {
  width: 100%;
  height: 48px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #7f7f7f;
  color: #fff;
  padding-inline: 24px;
  position: sticky;
  top: 0px;
  left: 0px;
  font-size: 18px;
}

.s-cropper-container .s-cropper-co {
  width: 100%;
}

.close-btn {
  display: flex;
  align-items: center;
  column-gap: 12px;
}
</style>
